/**
 * Project Name:dsrs-systemservice-web
 * File Name:DatadictController.java
 * Package Name:com.bwda.dsrs.systemservice.controller;
 * Date:2019年4月28日
 * Copyright (c) 2019, 江苏保旺达软件有限公司 All Rights Reserved.
 */
package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.systemservice.annotations.NeedRole;
import com.bwda.dsrs.systemservice.aspect.LogTypeEnum;
import com.bwda.dsrs.systemservice.aspect.Loggable;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.datadict.DatadictCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.datadict.DatadictCreateForm;
import com.bwda.dsrs.systemservice.domain.form.datadict.DatadictQueryForm;
import com.bwda.dsrs.systemservice.domain.form.datadict.DatadictUpdateForm;
import com.bwda.dsrs.systemservice.domain.po.datadict.DatadictPo;
import com.bwda.dsrs.systemservice.domain.vo.datadict.DatadictSelectVo;
import com.bwda.dsrs.systemservice.domain.vo.datadict.DatadictVo;
import com.bwda.dsrs.systemservice.service.DatadicTypeService;
import com.bwda.dsrs.systemservice.service.DatadictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典类型
 *
 * @author liangjianyong
 * @date 2019/4/11
 */
@RestController
@RequestMapping("/s/datadict")
@Api(value = "/s/datadict", tags = "数据字典")
public class DatadictController extends BaseController {

    @Autowired
    private DatadictService datadictService;

    @Autowired
    private DatadicTypeService datadicTypeService;


    @ApiOperation(value = "查询数据字典", notes = "查询数据字典", httpMethod = "GET")
    @Loggable(descp = "查询数据字典", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadictVo> query(@ApiParam(value = "字典ID", required = true)
                                                @RequestParam(value = "dataDictId") Long dataDictId) throws SystemServiceException {
        DatadictPo po = datadictService.queryWithValid(dataDictId);
        DatadictVo vo = CopyUtil.transfer(po, DatadictVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询数据字典(根据CODE查询)", notes = "查询数据字典(根据CODE查询)", httpMethod = "GET")
    @Loggable(descp = "查询数据字典(根据CODE查询)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadictVo> queryByCode(@ApiParam(value = "字典code", required = true)
                                                      @RequestParam(value = "dataDictCode") String dataDictCode) throws SystemServiceException {
        DatadictCondition condition = new DatadictCondition();
        condition.setDataDictCode(dataDictCode);
        condition.setStatus(Constants.StateType.ENABLE);
        List<DatadictPo> poList = datadictService.queryList(condition);
        DatadictPo po = new DatadictPo();
        if (poList != null && poList.size() == 1) {
            po = poList.get(0);
        }
        DatadictVo vo = CopyUtil.transfer(po, DatadictVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询数据字典列表(根据typeCode查询)", notes = "查询数据字典列表(根据typeCode查询)", httpMethod = "GET")
    @Loggable(descp = "查询数据字典列表(根据typeCode查询)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryListByTypeCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DatadictSelectVo>> queryListByTypeCode(@ApiParam(value = "字典类型code", required = true)
                                                                                        @RequestParam(value = "dataDictTypeCode") String dataDictTypeCode) {
        List<DatadictPo> datadictPoList = datadictService.selectValidListByListCode(dataDictTypeCode);
        List<DatadictSelectVo> selectVoList = new ArrayList<>();
        datadictPoList.forEach(data -> {
            DatadictSelectVo type = new DatadictSelectVo();
            type.setName(data.getDataDictName());
            type.setValue(data.getDataDictValue());
            selectVoList.add(type);
        });
        return getSuccessResult(getListResponse(selectVoList));
    }


    @ApiOperation(value = "查询数据字典数量", notes = "查询数据字典数量", httpMethod = "GET")
    @Loggable(descp = "查询数据字典数量", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@RequestBody @Valid DatadictQueryForm form) throws SystemServiceException {
        DatadictCondition condition = this.getConditionByQueryForm(form);
        int count = datadictService.queryCount(condition);
        return getSuccessResult(count);
    }


    @ApiOperation(value = "查询数据字典列表", notes = "查询数据字典列表", httpMethod = "GET")
    @Loggable(descp = "查询数据字典列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DatadictVo>> queryList(@RequestBody @Valid DatadictQueryForm form) throws SystemServiceException {
        DatadictCondition condition = this.getConditionByQueryForm(form);
        List<DatadictPo> poList = datadictService.queryList(condition);
        List<DatadictVo> voList = CopyUtil.transfer(poList, DatadictVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询数据字典列表(带分页)", notes = "查询数据字典列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "查询数据字典列表(带分页)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DatadictVo>> queryPageList(@ModelAttribute @Valid DatadictQueryForm form) throws SystemServiceException {
        DatadictCondition condition = this.getConditionByQueryForm(form);
        List<DatadictVo> voList = new ArrayList<>();
        int count = datadictService.queryCountWithTypeName(condition);
        if (count > 0) {
            List<DatadictPo> poList = datadictService.queryListWithTypeName(condition);
            voList = CopyUtil.transfer(poList, DatadictVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增数据字典", notes = "新增数据字典", httpMethod = "POST")
    @Loggable(descp = "新增数据字典", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadictVo> add(@ModelAttribute @Valid DatadictCreateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadictPo po = CopyUtil.transfer(form, DatadictPo.class);
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return getSuccessResult("获取不到用户");
        }
        po.setCreateUserCode(userCode);
        datadictService.insert(po);
        DatadictVo vo = CopyUtil.transfer(po, DatadictVo.class);
        return getSuccessResult(vo);
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增数据字典(跨服务使用)", notes = "新增数据字典(跨服务使用)", httpMethod = "POST")
    @Loggable(descp = "新增数据字典(跨服务使用)", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/addDatadict", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadictVo> addDatadict(@RequestBody @Valid DatadictCreateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadictPo po = CopyUtil.transfer(form, DatadictPo.class);
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return getSuccessResult("获取不到用户");
        }

        datadictService.insert(po);
        DatadictVo vo = CopyUtil.transfer(po, DatadictVo.class);
        return getSuccessResult(vo);
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "修改数据字典", notes = "修改数据字典", httpMethod = "POST")
    @Loggable(descp = "修改数据字典", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/updateWithRequestBody", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity updateWithRequestBody(@RequestBody @Valid DatadictUpdateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadictPo po = CopyUtil.transfer(form, DatadictPo.class);
        datadictService.update(po);
        return getSuccessResult();
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "修改数据字典", notes = "修改数据字典", httpMethod = "POST")
    @Loggable(descp = "修改数据字典", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid DatadictUpdateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadictPo po = CopyUtil.transfer(form, DatadictPo.class);
        String userCode = getUserCode();
        if (StringUtils.isBlank(userCode)) {
            logger.error("获取用户信息异常");
            return getSuccessResult("获取不到用户");
        }
        datadictService.update(po);
        return getSuccessResult();
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "删除数据字典", notes = "删除数据字典", httpMethod = "POST")
    @Loggable(descp = "删除数据字典", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@Valid @RequestParam(value = "id") List<Integer> id) throws SystemServiceException {
        if (id == null || id.size() == 0) {
            return getFailResult("参数错误");
        } else {
            return batchDelete(id);
        }
    }

    private ResponseEntity batchDelete(List<Integer> idList) throws SystemServiceException {
        //根据ID查询是否存在内置数据类型
        DatadictCondition defaultCondition = new DatadictCondition();
        defaultCondition.setIsDefault(Constants.IS_DEFAULT);
        defaultCondition.setIdList(idList);
        int count = datadictService.queryCountWithTypeName(defaultCondition);
        if (count > 0) {
            //如果ID列表包含内置对象,删除失败
            return getFailResult("内置数据不允许删除");
        } else {
            datadictService.batchDelete(idList);
        }
        return getSuccessResult();
    }


    @ApiOperation(value = "根据数据字典code查询value", notes = "根据数据字典code查询value", httpMethod = "POST")
    @Loggable(descp = "根据数据字典code查询value", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/getDataDictValByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> getDataDictValByCode(@ApiParam(value = "字典code", required = true) @RequestParam(value = "dataDictCode") String dataDictCode) throws SystemServiceException {
        String value = datadictService.getDataDictValByCode(dataDictCode);
        return getSuccessResult(Constants.SUCCESS, value);
    }

    @ApiOperation(value = "根据数据字典code查询value", notes = "根据数据字典code查询value", httpMethod = "POST")
    @Loggable(descp = "根据数据字典code查询value", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/getDataDictStringByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public String getDataDictStringByCode(@ApiParam(value = "字典code", required = true) @RequestParam(value = "dataDictCode") String dataDictCode) {
        String value = "";
        try {
            value = datadictService.getDataDictValByCode(dataDictCode);
        } catch (SystemServiceException e) {
            logger.error("查询dataDictCode失败：{}", dataDictCode);
        }
        return value;
    }


    @ApiOperation(value = "根据数据类型字典code查询value", notes = "根据数据类型字典code查询value", httpMethod = "POST")
    @Loggable(descp = "根据数据类型字典code查询value", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/getDataDictValByTypeCode", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DatadictPo> getDataDictValByTypeCode(@ApiParam(value = "字典code", required = true)
                                                         @RequestParam(value = "dataDictTypeCode") String dataDictTypeCode) throws SystemServiceException {
        List<DatadictPo> value = datadictService.getDataDictValByTypeCode(dataDictTypeCode);
        return value;
    }

    @ApiOperation(value = "根据数据类型字典code查询流程策略", notes = "根据数据类型字典code查询流程策略", httpMethod = "POST")
    @Loggable(descp = "根据数据类型字典code查询流程策略", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/getDataDictValForStrategy", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<List<DatadictPo>> getDataDictValForStrategy() throws SystemServiceException {
        List<DatadictPo> value = datadictService.getDataDictValByTypeCode(Constants.PROCESS_STRATEGY);
        return getSuccessResult(Constants.SUCCESS, value);
    }

    @ApiOperation(value = "根据数据字典code查询value(systemServiceApi)", notes = "根据数据字典code查询value", httpMethod = "POST")
    @Loggable(descp = "根据数据字典code查询value", type = LogTypeEnum.QUERY, include = "")
    @PostMapping(value = "/getSysDataDictValByCode")
    public ResponseEntity<String> getSysDataDictValByCode(@RequestBody String dataDictCode) throws SystemServiceException {
        String value = datadictService.getDataDictValByCode(dataDictCode);
        return getSuccessResult(Constants.SUCCESS, value);
    }

    @ApiOperation(value = "查询支持的上传文件类型", notes = "查询支持的上传文件类型", httpMethod = "POST")
    @Loggable(descp = "查询支持的上传文件类型", type = LogTypeEnum.QUERY, include = "")
    @PostMapping(value = "/getSupportUploadFileList")
    public ResponseEntity<String> getSupportUploadFileList() throws SystemServiceException {
        String value = datadictService.getDataDictValByCode("support_upload_type");
        return getSuccessResult(Constants.SUCCESS, value);
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "更新互斥字段状态", notes = "更新互斥字段状态", httpMethod = "POST")
    @Loggable(descp = "更新互斥字段状态", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/updateMutexStatusByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<String> updateMutexStatusByCode(@RequestParam String dataDictCode) {
        if (StringUtils.isBlank(dataDictCode)) {
            return getFailResult("修改失败");
        }
        //查询类型
        DatadictPo po = null;
        DatadictCondition condition = new DatadictCondition();
        condition.setDataDictCode(dataDictCode);
        List<DatadictPo> poList = datadictService.queryList(condition);
        if (poList != null && poList.size() == 1) {
            po = poList.get(0);
        }
        if (po == null) {
            return getFailResult("找不到对应记录");
        }
        //该类型下全部禁用
        datadictService.updateStatusByTypeCode(po.getDataDictTypeCode());
        DatadictPo updatePo = new DatadictPo();
        updatePo.setStatus(Constants.StateType.ENABLE);
        updatePo.setDataDictCode(dataDictCode);
        datadictService.update(updatePo);
        return getSuccessResult("更新成功");
    }


    @Loggable(descp = "根据数据字典code查询value", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/getDictValByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public String getDictValByCode(@RequestParam(value = "dataDictCode") String dataDictCode) throws SystemServiceException {
        String value = datadictService.getDataDictValByCode(dataDictCode);
        return value;
    }

    /**
     * DatadictQueryForm转换为DatadictCondition
     *
     * @param form
     * @return
     */
    private DatadictCondition getConditionByQueryForm(DatadictQueryForm form) {
        DatadictCondition condition = CopyUtil.transfer(form, DatadictCondition.class);
        return condition;
    }

}